// 导出一个axios的实例  而且这个实例要有请求拦截器 响应拦截器
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const timeOut = 1000 * 60 * 60
function IsTimeOut() {
  const current = Date.now()
  const pre = store.state.user.timeStamp
  return current - pre > timeOut
}

// 创建一个axios的实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
  // timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(function(config) {
  if (store.getters.token && IsTimeOut()) {
    store.dispatch('user/logout')
    router.push('/login')
    return Promise.reject('token已失效,请重新登录')
  }
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, function(error) {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
  const { message, success, data } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, (err) => {
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  } else {
    Message.error(err.message)
  }
  return Promise.reject(err)
})

// 导出axios实例
export default service
